var express = require("express");
var router = express.Router();
var fs = require('fs')
var { AdminModel } = require("../db/db");
var CompareFace = require('../untils/face')
// 登录接口
router.post("/login", async function (req, res) {
  //登录前查询数据库有无此账号
  const data = await AdminModel.find().where({
    username: req.body.username,
  });
  if (data.length == 0) {
    res.send({
      code: 500,
      message: "该用户没有注册,请先前往注册",
    });
    return;
  }
  // 验证密码
  if (data[0].pwd !== req.body.password) {
    res.send({
      code: 500,
      message: "密码错误,请重新验证",
    });
    return;
  }
  // 登录成功
  res.send({
    code: 200,
    message: '登陆成功',
    token: 'token123456',
    _id: data[0]._id
  })
});

// 人脸验证接口
router.post('/login/face/:_id', async (req, res) => {
  let base64 = req.body.base64 // 前端
  let _id = req.params._id
  let user = await AdminModel.findOne({ _id })
  if (!user.photo) {
    return res.send({
      code: 400,
      message: '该用户没有录入人脸信息!'
    })
  }
  let buffer = fs.readFileSync(user.photo)
  let baseA = buffer.toString('base64') // 后端
  let data = await CompareFace(baseA, base64).catch(e => e.message)
  if (data == '图片中没有人脸。') {
    return res.send({
      code: 400,
      message: '图片中没有人脸!'
    })
  }
  if (data.Score < 70) {
    return res.send({
      code: 400,
      message: '人脸验证不通过!'
    })
  }
  res.send({
    code: 200,
    message: '人脸验证成功!'
  })
})

// 用户详情
router.get('/info', async (req, res) => {
  let user = await AdminModel.findById(req.query.id)
  console.log(user);
  if (user) {
    res.send({
      code: 200,
      info: {
        name: user.username,
        avatar:
          "https://img2.baidu.com/it/u=1342701199,2079596281&fm=26&fmt=auto&gp=0.jpg",
        roles: ["admin"],
      },
      message: "信息返回成功",
    });
  } else {
    res.send({
      code: 200,
      info: {
        name: "请重新登录",
        avatar:
          "https://img2.baidu.com/it/u=1342701199,2079596281&fm=26&fmt=auto&gp=0.jpg",
        roles: ["admin"],
      },
      message: "登录token过期",
    });
  }
})

// 退出登录
router.post('/logout', (req, res) => {
  res.send({
    code: 200,
    message: '退出成功'
  })
})

// 注册接口
router.post('/register', async (req, res) => {
  await AdminModel.create(req.body)
  res.send({
    code: 200,
    msg: '注册成功!'
  })
})

// 判断用户是否已经注册
router.post('/is_register', async (req, res) => {
  let user = await AdminModel.findOne({ username: req.body.username })
  res.send({
    code: 200,
    user
  })
})

// base64文件图片上传接口
router.post('/upload/base64', async (req, res) => {
  let path = 'uploads/' + Date.now() + '.png'
  let base64 = req.body.base64
  let buffer = Buffer.from(base64, 'base64')
  fs.writeFileSync(path, buffer)
  res.send({
    code: 200,
    message: '文件上传成功!',
    path
  })
})

// 人脸验证登录,获取符合信息
router.post('/facelogin', async (req, res) => {
  let users = await AdminModel.find({ photo: { $ne: null } })
  let base64 = req.body.base64 // 前端
  let right = []
  for (let user of users) {
    let buffer
    try {
      buffer = fs.readFileSync(user.photo)
    } catch {
      continue
    }
    let baseA = buffer.toString('base64') // 后端
    let data = await CompareFace(baseA, base64).catch(e => e.message)

    if (data == '图片中没有人脸。' || data.Score < 70) continue
    right.push({ id: user._id, username: user.username })
  }
  res.send({ code: 200, users: right })
})

// 直接根据人脸匹配id进行登录
router.post('/submitfacelogin', async (req, res) => {
  res.send({
    code: 200,
    message: '登陆成功',
    token: 'token123456',
    _id: req.body.id
  })
})




//修改密码
router.post('/changePwd', async (req, res) => {
  let obj = req.body
  console.log(obj,'obj')
 await AdminModel.updateOne({_id:obj.id},{pwd:obj.pwd})
  res.send({
    code: 200,
    message: '修改成功',
    _id: req.body.id
  })
})

module.exports = router;